<?php

/**
 * @author dungdhs@gmail.com
 * @copyright 2012
 */

function admin_task(){
  return array(
    'default' => array(
      'func'  => '_admin_dashboard',
      'perm'  => 'admin dashboard',
			'title'	=> 'Admin Dashboard' 
    ),
    
    'cron' => array(
      'func'  => '_admin_cron',
      'perm'  => 'admin dashboard',
			'title'	=> 'Admin Dashboard' 
    ),
    
    'permission' => array(
      'func'  => '_admin_permission',
      'perm'  => 'admin permission',
      'title' => 'Quản lý quyền truy cập'
    )
  );
}

function _admin_dashboard(){
	global $smarty;
	cheader('news/admin');
	return $smarty->fetch('admin_dashboard.tpl');
}

function _admin_permission(){
  global $database, $smarty;
  
  $aRole = system_role();
  $aPerm = system_permission();
  
  if (count($_POST)>0){
    $database->db_query("DELETE FROM role_permissions");
    foreach ($aRole as $roleId=>$role)
      foreach ($aPerm as $permId=>$perm)
      if (isset($_POST[$roleId][$perm['permission_name']])){
        $database->db_query("INSERT INTO role_permissions(rp_role_id, rp_permission, rp_module) VALUES (%d, '%s', '%s')", $roleId, $perm['permission_name'], $perm['permission_module']);
      }
      
    cheader('admin/permission');
  }
  
  $aModulePerm = array();
  foreach ($aPerm as $perm){
    $aModulePerm[$perm['permission_module']][$perm['permission_name']] = array();
  }
  
  $aRolePerm = system_role_permission();
  
  $smarty->assign('aRolePerm', $aRolePerm);
  $smarty->assign('aModulePerm', $aModulePerm);
  $smarty->assign('aRole', $aRole);
  $smarty->assign('colSpan', count($aRole)+1);
  
  return $smarty->fetch('admin_permission.tpl');
}

function _admin_cron(){
	global $database;
	
	// UPDATE news URL
	$res = $database->db_query("SELECT * FROM news ORDER BY news_id ASC");
	while ($news = $database->db_fetch_assoc($res)){
		$cat = __category_get($news['news_cat_id']);
    if ($cat){
      url_set_alias('news/detail/'.$news['news_id'], $cat['cat_title'].'/'.$news['news_title']);
    }else{
      url_set_alias('news/detail/'.$news['news_id'], $news['news_title']);
    }
	}
	
	// UPDATE news URL
	$res = $database->db_query("SELECT * FROM categories ORDER BY cat_id ASC");
	while ($r = $database->db_fetch_assoc($res)){
		switch ($r['cat_type']){
			case 'news':
				url_set_alias('category/detail/'.$r['cat_id'], $r['cat_title']); break;
			case 'product':
				url_set_alias('product/cat/'.$r['cat_id'], $r['cat_title']); break;
			case 'collection':
				url_set_alias('collection/cat/'.$r['cat_id'], $r['cat_title']); break;
		}
	}
	
	PGTheme::set_message('Đã chạy cron thành công!');
	cheader('<front>');
}